package cn.xmall.utills;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.lang.reflect.Type;

/**
 * Created by MoTaiXian on 2017/7/18.
 */

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
    static final byte[] EMPTY_ARRAY = new byte[0];

    private  Class<T> clazz;

    public  FastJsonRedisSerializer(){
        this((Class<T>) Object.class);
    }

    public FastJsonRedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T o) throws SerializationException {
        if(o == null) {
            return EMPTY_ARRAY;
        }else {
            try{
                return JSON.toJSONBytes(o,SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteClassName);

            }catch(Exception e){
                throw new SerializationException("Could not write JSON: " + e.getMessage(), e);

            }
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if(bytes==null || bytes.length==0) {
            return null;
        } else {
            try {
                return (T)JSON.parseObject(bytes,clazz);
            } catch (Exception e) {
                throw new SerializationException("Could not read JSON: " + e.getMessage(), e);
            }
        }
    }

}
